from snippets.models import Snippet
from snippets.serializers import SnippetSerializer, UserSerializer
from rest_framework import generics
from django.contrib.auth.models import User
from rest_framework import permissions
from snippets.permissions import IsOwnerOrReadOnly
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework import renderers, viewsets
from rest_framework.decorators import action
from django_filters.rest_framework.backends import DjangoFilterBackend
from rest_framework.filters import OrderingFilter, SearchFilter


# 使用REST框架的reverse功能来返回完全合格的URL。
@api_view(['GET'])
def api_root(request, format=None):
    return Response(
        {
            'users': reverse('user-list', request=request, format=format),
            'snippets': reverse('snippet-list', request=request, format=format)
        }
    )


# class SnippetList(generics.ListCreateAPIView):
#     queryset = Snippet.objects.all()
#     serializer_class = SnippetSerializer
#     permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
#
#     def perform_create(self, serializer):
#         serializer.save(owner=self.request.user)
#
#
# class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
#     queryset = Snippet.objects.all()
#     serializer_class = SnippetSerializer
#     permission_classes = (permissions.IsAuthenticatedOrReadOnly,
#                           IsOwnerOrReadOnly,)
#
# class SnippetHighlight(generics.GenericAPIView):
#     queryset = Snippet.objects.all()
#     renderer_classes = (renderers.StaticHTMLRenderer,)
#
#     def get(self, request, *args, **kwargs):
#         snippet = self.get_object()
#         return Response(snippet.highlighted)

# class UserList(generics.ListAPIView):
#     queryset = User.objects.all()
#     serializer_class = UserSerializer
#
#
# class UserDetail(generics.RetrieveAPIView):
#     queryset = User.objects.all()
#     serializer_class = UserSerializer


class UserViewSet(viewsets.ReadOnlyModelViewSet):
    """
    这个视图集自动提供 `list` 和 `detail` 操作。
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer
    lookup_field = 'username'


class SnippetViewSet(viewsets.ModelViewSet):
    """
    这个视图集自动提供 `list`，`create`，`retrieve`，`update`和`destroy`操作。

    另外我们还提供了一个额外的 `highlight` 操作。
    """
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    permission_classes = (
        permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
    # lookup_url_kwarg = 'code'
    # lookup_field = 'code'
    filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter]
    filter_fields = ['code']
    search_fields = ['code', 'owner__username']
    ordering_fields = ['owner', 'code']  # 这里写'url'会报错，报错会提示有哪些字段可以排序
    # 使用ordering指定默认排序（不输入上面的指端指定排序则使用以下默认字段）
    ordering = ['code']

    # 这里url_name不写也可以，默认就是方法名，但在serializers中使用时，是用snippet-highlight
    @action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer],
            url_path='highlight-show', url_name='highlight')
    def highlight(self, request, *args, **kwargs):
        snippet = self.get_object()
        return Response(snippet.highlighted)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)


class SnippetList(generics.ListAPIView):
    """
    此视图应返回当前已验证用户的所有 purchases 列表。
    """
    serializer_class = SnippetSerializer

    def get_queryset(self):
        user = self.request.user
        return Snippet.objects.filter(owner=user)

    @action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer],
            url_path='highlight-show', url_name='highlight')
    def highlight(self, request, *args, **kwargs):
        snippet = self.get_object()
        return Response(snippet.highlighted)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)
